<template>
  <div class="member-level">
    <el-card class="box-card">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增等级</el-button>
      </div>

      <!-- 等级列表 -->
      <el-table
        v-loading="loading"
        :data="levelList"
        border
        row-key="id"
        :default-sort="{prop: 'level', order: 'ascending'}"
      >
        <el-table-column prop="level" label="等级" width="80" sortable></el-table-column>
        <el-table-column prop="name" label="等级名称" min-width="120"></el-table-column>
        <el-table-column prop="icon" label="等级图标" width="100">
          <template slot-scope="scope">
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.icon"
              :preview-src-list="[scope.row.icon]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="minPoints" label="所需积分" width="120" sortable>
          <template slot-scope="scope">
            {{ scope.row.minPoints.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="折扣率" width="100">
          <template slot-scope="scope">
            {{ scope.row.discount }}%
          </template>
        </el-table-column>
        <el-table-column prop="pointsRate" label="积分比例" width="100">
          <template slot-scope="scope">
            {{ scope.row.pointsRate }}%
          </template>
        </el-table-column>
        <el-table-column label="等级权益" min-width="200">
          <template slot-scope="scope">
            <el-tag
              v-for="benefit in scope.row.benefits"
              :key="benefit.id"
              size="small"
              style="margin-right: 5px; margin-bottom: 5px"
            >
              {{ benefit.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              size="mini"
              :disabled="scope.row.level === 1"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="levelForm" :rules="rules" ref="levelForm" label-width="100px">
        <el-form-item label="等级" prop="level">
          <el-input-number 
            v-model="levelForm.level" 
            :min="1"
            :disabled="!!editingLevel"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="levelForm.name" placeholder="请输入等级名称"></el-input>
        </el-form-item>
        <el-form-item label="等级图标" prop="icon">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleIconSuccess"
            :before-upload="beforeIconUpload"
          >
            <img v-if="levelForm.icon" :src="levelForm.icon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="所需积分" prop="minPoints">
          <el-input-number 
            v-model="levelForm.minPoints" 
            :min="0"
            :step="100"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="折扣率" prop="discount">
          <el-input-number 
            v-model="levelForm.discount" 
            :min="0"
            :max="100"
            :precision="1"
          >
            <template slot="append">%</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="积分比例" prop="pointsRate">
          <el-input-number 
            v-model="levelForm.pointsRate" 
            :min="0"
            :max="100"
            :precision="1"
          >
            <template slot="append">%</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="等级权益" prop="benefits">
          <el-checkbox-group v-model="levelForm.benefits">
            <el-checkbox 
              v-for="benefit in benefitOptions" 
              :key="benefit.id"
              :label="benefit.id"
            >
              {{ benefit.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="levelForm.status"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            v-model="levelForm.description"
            :rows="3"
            placeholder="请输入等级描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMemberLevelList,
  createMemberLevel,
  updateMemberLevel,
  deleteMemberLevel,
  getMemberLevelBenefits
} from '@/api/memberLevels'

export default {
  name: 'MemberLevel',
  data() {
    return {
      // 加载状态
      loading: false,
      // 等级列表
      levelList: [],
      // 权益选项
      benefitOptions: [],
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '新增等级',
      // 正在编辑的等级
      editingLevel: null,
      // 等级表单
      levelForm: {
        level: 1,
        name: '',
        icon: '',
        minPoints: 0,
        discount: 100,
        pointsRate: 1,
        benefits: [],
        status: 1,
        description: ''
      },
      // 表单验证规则
      rules: {
        level: [
          { required: true, message: '请输入等级', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入等级名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请上传等级图标', trigger: 'change' }
        ],
        minPoints: [
          { required: true, message: '请输入所需积分', trigger: 'blur' }
        ],
        discount: [
          { required: true, message: '请输入折扣率', trigger: 'blur' }
        ],
        pointsRate: [
          { required: true, message: '请输入积分比例', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
    this.fetchBenefits()
  },
  methods: {
    // 获取数据
    async fetchData() {
      try {
        this.loading = true
        const res = await getMemberLevelList()
        this.levelList = res.data
      } catch (error) {
        console.error('获取会员等级列表失败：', error)
        this.$message.error('获取会员等级列表失败')
      } finally {
        this.loading = false
      }
    },
    // 获取权益选项
    async fetchBenefits() {
      try {
        const res = await getMemberLevelBenefits()
        this.benefitOptions = res.data
      } catch (error) {
        console.error('获取权益列表失败：', error)
        this.$message.error('获取权益列表失败')
      }
    },
    // 新增等级
    handleAdd() {
      this.editingLevel = null
      this.dialogTitle = '新增等级'
      // 获取最大等级
      const maxLevel = Math.max(...this.levelList.map(item => item.level), 0)
      this.levelForm = {
        level: maxLevel + 1,
        name: '',
        icon: '',
        minPoints: 0,
        discount: 100,
        pointsRate: 1,
        benefits: [],
        status: 1,
        description: ''
      }
      this.dialogVisible = true
    },
    // 编辑等级
    handleEdit(row) {
      this.editingLevel = row
      this.dialogTitle = '编辑等级'
      this.levelForm = {
        ...row,
        benefits: row.benefits.map(item => item.id)
      }
      this.dialogVisible = true
    },
    // 提交表单
    async handleSubmit() {
      this.$refs.levelForm.validate(async valid => {
        if (valid) {
          try {
            const isEdit = !!this.editingLevel
            const apiMethod = isEdit ? updateMemberLevel : createMemberLevel
            const data = { ...this.levelForm }
            
            if (isEdit) {
              await apiMethod(this.editingLevel.id, data)
            } else {
              await apiMethod(data)
            }
            
            this.$message.success(`${isEdit ? '编辑' : '新增'}成功`)
            this.dialogVisible = false
            this.fetchData()
          } catch (error) {
            console.error('保存失败：', error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    // 删除等级
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该等级?', '提示', {
          type: 'warning'
        })
        await deleteMemberLevel(row.id)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败：', error)
          this.$message.error('删除失败')
        }
      }
    },
    // 更新状态
    async handleStatusChange(row) {
      try {
        await updateMemberLevel(row.id, { status: row.status })
        this.$message.success('状态更新成功')
      } catch (error) {
        console.error('状态更新失败：', error)
        this.$message.error('状态更新失败')
        row.status = row.status === 1 ? 0 : 1
      }
    },
    // 图标上传成功
    handleIconSuccess(res, file) {
      this.levelForm.icon = res.url
    },
    // 图标上传前校验
    beforeIconUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图标只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图标大小不能超过 2MB!')
      }
      return isImage && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.member-level {
  .toolbar {
    margin-bottom: 20px;
  }

  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;

    &:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }

    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
  }
}
</style> 